
import Router from '../js/router/router'

const MODE = 'history';// hash history

class App {
  constructor() {
    console.log('app')
    this.isPropstate = false;
    this.router = new Router({
      mode: MODE
    })
    this.initEvent();
    this.initSwipper();
  }


  initEvent() {
    var self = this;
    $("#nav li").on('touchstart', function () {
      $(this).addClass('active').siblings().removeClass('active')
      let index = $(this).index();
      self.mySwiper.slideTo(index, 300, false);
    })

    //页面刷新,首次加载页面
    addEventListener('load', () => {
      let url = location.hash.replace('#', '') || 'position';
      if (MODE === 'history') {
        url = history.state ? history.state.path : 'position';
      }
      self.router.go(url)
      this.slideToSwipper(url);
      this.setActive(url);
    })


    //浏览器的前进和后退
    if (MODE === 'hash') {
      addEventListener('hashchange', () => {
        let hash = location.hash.replace('#', '');
        this.slideToSwipper(hash)
        this.setActive(hash);
      })
    } else {
      $(window).on('popstate', () => {
        console.log(history.state)
        let url = history.state.path;
        this.isPropstate = true;
        // self.router.go(url);
        this.slideToSwipper(url)
        this.router.loadView(url);
        this.setActive(url);
      })
    }
  }

  //根据url，切换到对应的swipper
  slideToSwipper(url) {
    let index = $("#nav").find('li[data-url="' + url + '"]').index();
    this.mySwiper.slideTo(index, 300, false);
  }

  //设置菜单的激活状态
  setActive(url) {
    $("#nav").find("li[data-url='" + url + "']").addClass('active').siblings().removeClass('active');

  }


  initSwipper() {
    var self = this;
    this.mySwiper = new Swiper('.swiper-container', {
      // loop: true,
      on: {
        slideChange: function () {
          let cur = $("#nav").find('li').eq(this.activeIndex);
          let url = cur.attr('data-url');
          if (!self.isPropstate) {
            self.router.go(url)
          }
          self.isPropstate = false;
        }
      },
    })

  }


}

new App();